package com.youmu.shop.monitor;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import com.common.util.ExceptionUtil;
import com.common.util.MapConvertUtil;
import com.result.Result;

import net.sf.json.JSONObject;


public class AnnotationHandlerMethodExceptionResolver extends ExceptionHandlerExceptionResolver {
    protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {
        if (handlerMethod == null) {
            return null;
        }
        Method method = handlerMethod.getMethod();
        handlerMethod.getMethodAnnotation(Controller.class);
        if (method == null) {
            return null;
        }
        Result result= ExceptionUtil.handleException(exception);
        ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method, ResponseBody.class);
        if (responseBodyAnn != null) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer;
            try {
                writer = response.getWriter();
                logger.error(exception.getMessage(), exception);
            writer.write(JSONObject.fromObject(result).toString());
            writer.flush();
            writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return new ModelAndView("/error", MapConvertUtil.bean2Map(result));
        }
        return null;
        
    }
}

